package cn.mickey.exchange.service;

import cn.mickey.exchange.config.AliyunOssConfig;
import cn.mickey.exchange.properties.LocalUploadProperties;
import com.aliyun.oss.OSS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@Service
@Slf4j
public class FileService {

    @Resource
    private LocalUploadProperties localUploadProperties;

    @Resource
    private OSS ossClient;

    @Resource
    private AliyunOssConfig aliyunOssConfig;

    public boolean uploadFile(MultipartFile multipartFile, String fileName) throws IOException {
        File fileDir = new File(localUploadProperties.getUserFilePath());
        if (!fileDir.exists()) {
            if (!fileDir.mkdirs()) {
                return false;
            }
        }
        File file = new File(fileDir.getAbsolutePath() + "/" + fileName);
        if (file.exists()) {
            if (!file.delete()) {
                return false;
            }
        }
        if (file.createNewFile()) {
            multipartFile.transferTo(file);
            return true;
        }
        return false;
    }

    public String uploadImage(String fileName, MultipartFile multipartFile) {
        String objectName = "idle-exchange/" + fileName;
        try {
            //上传到oss
            ossClient.putObject(aliyunOssConfig.getBucketName(), objectName, multipartFile.getInputStream());
            // 设置URL过期时间为60s。
            //Date expiration = new Date(System.currentTimeMillis() + 60);
            // 60s就会过期的url
            //String unprocessedUrl = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
            //获取上传图片的url
            return aliyunOssConfig.getUrlPrefix() + objectName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}